#!/usr/bin/env python3
# -*- encoding: utf-8 -*-

__author__ = "Yunpeng Li <ypli.chn@outlook.com.com>"
from EU.models import Complaint
from django.utils import timezone
from datetime import datetime
from django.db import DatabaseError
from EU.admin.StatusCode import StatusCode
from django.utils import timezone
import json

def post_complaints(device_id,message,name,phone,mail):
    complaint = Complaint()
    complaint.message = message
    complaint.date = timezone.now()
    complaint.name = name
    complaint.phone = phone
    complaint.mail = mail

    result = {}
    try:
         complaint.save()
    except DatabaseError as e:
        print(e)
        result['status'] = StatusCode.DBError
        result['message'] = "数据库错误"
    else:
        result['status'] = StatusCode.Success
        result['message'] = "Success"
    return json.dumps(result)


def get_complaints(timestamp):
    print(timestamp)
    # timezone.datetime = None
    try:
        print(datetime.fromtimestamp(float(timestamp)))
        time = timezone.make_aware(datetime.fromtimestamp(float(timestamp)))
        result = []
        complaints = Complaint.objects.filter(date__lte=time)#.all()#filter(time__lte=time)
        for complaint in complaints:
            result.append({
                "date":complaint.date.timestamp(),
                "message":complaint.message,
                "phone":complaint.phone,
                "mail":complaint.mail,
            })
    except Exception as e:
        result['status'] = StatusCode.IllegalAttribute
        result['message'] = "参数错误"
    print(result)
    return json.dumps(result)